package com.open.capacity.forum.controller;

import com.open.capacity.common.exception.controller.ControllerException;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.forum.constant.BusinessConstant;
import com.open.capacity.forum.constant.MetasConstant;
import com.open.capacity.forum.dto.ArticleDto;
import com.open.capacity.forum.model.*;
import com.open.capacity.forum.service.*;
import com.open.capacity.log.annotation.LogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@Api(tags = "Article API")
@Slf4j
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleTagsSerivce tagsSerivce;
    @Resource
    private ArticleCategoryService categoryService;
    @Resource
    private MetasService metasService;


    @GetMapping("page")
    @ApiOperation(value = "文章分页条件查询")
    @LogAnnotation(module = "forum-center")
    public PageResult articlePage(@RequestParam Map<String, Object> params) throws ControllerException {
        try {
            return articleService.findArticlePage(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @GetMapping("blogPage")
    @ApiOperation(value = "博客文章页条件查询")
    @LogAnnotation(module = "forum-center")
    public PageResult blogPage(@RequestParam Map<String, Object> params) throws ControllerException {
        try {
            return articleService.findBlogPage(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @PostMapping("saveOrUpdate")
    @ApiOperation(value = "文章添加或更新")
    @LogAnnotation(module = "forum-center")
    public Result saveOrUpdate(@RequestBody ArticleDto article) throws ControllerException {
        try {
            boolean saveOrUpdate = articleService.saveOrUpdate(article);
            if (saveOrUpdate) {
                if (article.getCreatedCategories() != null)
                    articleService.createdCategiryToArticle(article.getArleid(), article.getCreatedCategories());
                else if (article.getAppendCategories() != null) {
                    List<ArticleCategoryRelation> categoryRelations = new ArrayList<>();
                    for (ArticleCategory appendCategory : article.getAppendCategories())
                        categoryRelations.add(ArticleCategoryRelation.builder().arleid(article.getArleid()).cateid(appendCategory.getCateid()).build());
                    articleService.appendCategoryToArticle(categoryRelations);
                }
            }
            return saveOrUpdate ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }

    @DeleteMapping("{articleId}")
    @ApiOperation(value = "根据文章id删除文章")
    @LogAnnotation(module = "forum-center")
    public Result deleteArticledById(@PathVariable Long articleId) throws ControllerException {
        try {
            return articleService.deleteArticleById(articleId);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @GetMapping("tags/{userId}")
    @ApiOperation(value = "查询用户创建的文章标签")
    @LogAnnotation(module = "forum-center")
    public List<ArticleTags> queryTagsByUserId(@PathVariable Long userId) throws ControllerException {
        try {
            return tagsSerivce.findByUserId(userId);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @PostMapping("tags")
    @ApiOperation(value = "文章标签添加或更新")
    @LogAnnotation(module = "forum-center")
    public Result saveOrUpdateArticleTags(@RequestBody ArticleTags articleTags) throws ControllerException {
        //noinspection Duplicates
        try {
            return tagsSerivce.saveOrUpdate(articleTags) ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @DeleteMapping("tags/{id}")
    @ApiOperation(value = "文章标签删除")
    @LogAnnotation(module = "forum-center")
    public Result deleteArticleTags(@PathVariable Integer id) {
        //noinspection Duplicates
        try {
            return tagsSerivce.removeById(id) ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @PostMapping("tags/batchSave")
    @ApiOperation(value = "文章标签批量添加")
    @LogAnnotation(module = "forum-center")
    public Result batchSaveOfTags(@RequestBody List<ArticleTags> articleTagsList) throws ControllerException {
        //noinspection Duplicates
        try {
            return tagsSerivce.saveBatch(articleTagsList) ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @GetMapping("articleType")
    @ApiOperation(value = "查询文章类型")
    @LogAnnotation(module = "forum-center")
    public List<Metas> queryArticleType() {
        return metasService.findMetasByTypeCode(MetasConstant.ARTICLE_TYPE);
    }

    @GetMapping("articleState")
    @ApiOperation(value = "查询文章状态")
    @LogAnnotation(module = "forum-center")
    public List<Metas> queryArticleState() {
        return metasService.findMetasByTypeCode(MetasConstant.ARTICLE_STATE);
    }

    @GetMapping("category/page")
    @ApiOperation(value = "文章分类专栏分页条件查询")
    @LogAnnotation(module = "forum-center")
    public PageResult categoryPage(@RequestParam Map<String, Object> params) throws ControllerException {
        try {
            return categoryService.findArticleCategoryPage(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @GetMapping("category/{userId}")
    @ApiOperation(value = "查询用户创建的文章分类专栏")
    @LogAnnotation(module = "forum-center")
    public List<ArticleCategory> queryArticleCategory(@PathVariable Long userId) throws ControllerException {
        try {
            return categoryService.findArticleCategoryByUserId(userId);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @PostMapping("category/saveOrUpdate")
    @ApiOperation(value = "文章分类专栏添加或更新")
    @LogAnnotation(module = "forum-center")
    public Result saveOrUpdateArticleCategory(@RequestBody ArticleCategory category) throws ControllerException {
        //noinspection Duplicates
        try {
            return categoryService.saveOrUpdate(category) ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @PostMapping("category/batchSave")
    @ApiOperation(value = "文章分类专栏批量添加")
    @LogAnnotation(module = "forum-center")
    public Result batchSaveOfCategory(@RequestBody List<ArticleCategory> articleCategories) throws ControllerException {
        //noinspection Duplicates
        try {
            boolean saveBatch = categoryService.saveBatch(articleCategories);
            return saveBatch ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @DeleteMapping("category/{categoryIds}")
    @ApiOperation(value = "文章分类专栏批量删除")
    @LogAnnotation(module = "forum-center")
    public Result batchDeleteCategory(@PathVariable List<Integer> categoryIds) {
        //noinspection Duplicates
        try {
            return categoryService.removeByIds(categoryIds) ? Result.succeed(BusinessConstant.Default.succeed) : Result.failed(BusinessConstant.Default.failed);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @PostMapping("category/created/{articleId}")
    @ApiOperation(value = "新创建用户文章的分类专栏")
    @LogAnnotation(module = "forum-center")
    public Result createdCategory(@PathVariable Integer articleId, @RequestBody List<ArticleCategory> articleCategories) throws ControllerException {
        //noinspection Duplicates
        try {
            return articleService.createdCategiryToArticle(articleId, articleCategories);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }

    @PostMapping("category/append")
    @ApiOperation(value = "追加用户文章的分类专栏")
    @LogAnnotation(module = "forum-center")
    public Result appendCategory(@RequestBody List<ArticleCategoryRelation> categoryRelations) throws ControllerException {
        try {
            return articleService.appendCategoryToArticle(categoryRelations);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @DeleteMapping("category/removed/{articleId}")
    @ApiOperation(value = "移除用户文章的分类专栏")
    @LogAnnotation(module = "forum-center")
    public Result removedCategory(@PathVariable Integer articleId, Integer[] ids) throws ControllerException {
        //noinspection Duplicates
        try {
            return articleService.removeArticleCategory(articleId, ids);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new ControllerException(e);
        }
    }
}
